<template>
  <view class="search-container">
    <!-- 搜索头部 -->
    <view class="search-header">
      <view class="search-input-wrapper">
        <image src="https://zxs-lyblog.oss-cn-hangzhou.aliyuncs.com/2025-06-21/search-icon.png" mode="aspectFit" class="search-icon" />
        <input 
          type="text" 
          class="search-input" 
          placeholder="搜索文章、话题、用户" 
          v-model="searchKeyword" 
          @confirm="handleSearch" 
          @input="handleInputChange" 
          auto-focus
        />
        <view v-if="searchKeyword" class="clear-btn" @click="clearSearch">
          <image src="https://zxs-lyblog.oss-cn-hangzhou.aliyuncs.com/2025-06-21/clear-icon.png" mode="aspectFit" />
        </view>
      </view>
    </view>

    <!-- 搜索结果 -->
    <view class="search-results" v-if="showResults">
      <!-- 搜索历史 -->
      <view v-if="!searchKeyword" class="history-section">
        <view class="section-header">
          <text>搜索历史</text>
          <view class="clear-history" @click="clearHistory">
            <image src="https://zxs-lyblog.oss-cn-hangzhou.aliyuncs.com/2025-06-21/history-clear.png" mode="aspectFit" />
            <text>清空</text>
          </view>
        </view>
        <view class="history-list">
          <view class="history-item" v-for="(item, index) in searchHistory" :key="index" @click="searchWithHistory(item)">
            <text>{{ item }}</text>
          </view>
        </view>
      </view>

      <!-- 热门搜索 -->
      <view v-if="!searchKeyword" class="hot-section">
        <view class="section-header">
          <text>热门搜索</text>
        </view>
        <view class="hot-list">
          <view class="hot-item" v-for="(item, index) in hotSearches" :key="index" @click="searchWithHot(item.keyword)">
            <view class="hot-rank" :class="{ 'top-three': index < 3 }">
              <text>{{ index + 1 }}</text>
            </view>
            <text>{{ item.keyword }}</text>
          </view>
        </view>
      </view>

      <!-- 搜索结果列表 -->
      <view v-else-if="searchResults.length > 0" class="results-list">
        <view class="article-item" v-for="(item, index) in searchResults" :key="index" @click="navigateToDetail(item)">
          <!-- 作者信息 -->
          <view class="user-info">
            <image :src="item.avatarUrl || 'https://zxs-lyblog.oss-cn-hangzhou.aliyuncs.com/2025-06-21/default-avatar.png'" mode="aspectFit" class="user-image" />
            <view class="user-name">{{ item.authorName }}</view>
          </view>

          <!-- 文章主题 -->
          <view class="article-main">
            <view class="article-content">
              <view class="article-title">{{ item.title }}</view>
              <view class="article-subtitle">{{ item.subtitle }}</view>
            </view>
            <image v-if="item.coverUrl" :src="item.coverUrl" mode="aspectFill" class="article-url" />
          </view>

          <view class="article-footer">
            <!-- 文章阅读量 -->
            <view class="article-read">
              <image src="https://zxs-lyblog.oss-cn-hangzhou.aliyuncs.com/2025-06-21/read.png" 
                mode="aspectFill" />
              <text>{{ item.readCount }}</text>
            </view>

            <!-- 文章点赞量 -->
            <view class="article-read">
              <image v-if="!item.likeFlg" 
                src="https://zxs-lyblog.oss-cn-hangzhou.aliyuncs.com/2025-06-21/no-like.png" 
                mode="aspectFill" />
              <image v-else src="https://zxs-lyblog.oss-cn-hangzhou.aliyuncs.com/2025-06-21/liked.png" 
                mode="aspectFill" />
              <text>{{ item.likeCount }}</text>
            </view>

            <!-- 文章收藏量 -->
            <view class="article-read">
              <image v-if="!item.favoriteFlg" 
                src="https://zxs-lyblog.oss-cn-hangzhou.aliyuncs.com/2025-06-21/no-collect.png" 
                mode="aspectFill" />
              <image v-else src="https://zxs-lyblog.oss-cn-hangzhou.aliyuncs.com/2025-06-21/collected.png" 
                mode="aspectFill" />
              <text>{{ item.favoriteCount }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 无搜索结果 -->
      <view v-else-if="searchKeyword && searchResults.length === 0" class="no-results">
        <image src="https://zxs-lyblog.oss-cn-hangzhou.aliyuncs.com/2025-06-21/no-result.png" mode="aspectFit" class="no-result-icon" />
        <text>暂无相关内容</text>
        <text class="tips">换个关键词试试吧</text>
      </view>

      <!-- 加载中 -->
      <view v-if="loading" class="loading">
        <text>搜索中...</text>
      </view>
    </view>
  </view>
</template>

<script>
import { generateMockResults, hotSearches } from '../../mock/search.js';

export default {
  data() {
    return {
      searchKeyword: '',
      searchResults: [],
      loading: false,
      showResults: true,
      searchHistory: [],
      hotSearches: hotSearches
    };
  },
  onLoad(options) {
  	if (options.keyword) {
		this.searchKeyword = options.keyword;
  		this.handleSearch();
  	}else{
		this.loadSearchHistory();
	}
  },
  methods: {
    // 处理输入变化
    handleInputChange() {
      // 当输入框内容变化时，如果有搜索结果就清空
      if (this.searchResults.length > 0) {
        this.searchResults = [];
      }
    },

    // 处理搜索
    async handleSearch() {
      if (!this.searchKeyword.trim()) return;

      this.loading = true;
      
      try {
        // 模拟搜索API调用
        await new Promise(resolve => setTimeout(resolve, 500));
        
        // 这里应该是实际的API调用，现在使用模拟数据
        // const data = await this.$api.article.searchArticles({ keyword: this.searchKeyword });
        
        // 模拟搜索结果
        const mockResults = generateMockResults(this.searchKeyword);
        this.searchResults = mockResults;
        
        // 保存搜索历史
        this.saveSearchHistory(this.searchKeyword.trim());
      } catch (error) {
        console.error('搜索失败:', error);
        uni.showToast({
          title: '搜索失败，请重试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },

    // 跳转到文章详情
    navigateToDetail(item) {
      uni.navigateTo({
        url: `/pages/article/article?articleid=${item.articleId}`
      });
    },

    // 取消搜索
    cancelSearch() {
      uni.navigateBack();
    },

    // 清空搜索
    clearSearch() {
      this.searchKeyword = '';
      this.searchResults = [];
    },

    // 加载搜索历史
    loadSearchHistory() {
      const history = uni.getStorageSync('searchHistory');
      this.searchHistory = history ? JSON.parse(history) : [];
    },

    // 保存搜索历史
    saveSearchHistory(keyword) {
      // 去重
      if (!this.searchHistory.includes(keyword)) {
        this.searchHistory.unshift(keyword);
        // 只保留最近10条历史记录
        if (this.searchHistory.length > 10) {
          this.searchHistory = this.searchHistory.slice(0, 10);
        }
        uni.setStorageSync('searchHistory', JSON.stringify(this.searchHistory));
      }
    },

    // 清空搜索历史
    clearHistory() {
      uni.showModal({
        title: '提示',
        content: '确定要清空搜索历史吗？',
        success: (res) => {
          if (res.confirm) {
            this.searchHistory = [];
            uni.removeStorageSync('searchHistory');
          }
        }
      });
    },

    // 使用历史记录搜索
    searchWithHistory(keyword) {
      this.searchKeyword = keyword;
      this.handleSearch();
    },

    // 使用热门搜索
    searchWithHot(keyword) {
      this.searchKeyword = keyword;
      this.handleSearch();
    }
  }
};
</script>

<style lang="scss" scoped>
@import './search.scss';
</style>